<?php
namespace Duobao\Model;

use Think\Model;
use Duobao\Controller\LogController as Mylog;

class MemberModel extends Model
{

    protected $tableName = 'member ';

    /**
     * 获取用户显示的名称
     *
     * @param string|array $uid            
     * @param string $type            
     * @param string $key            
     * @return string array
     */
    public function getShowName($uid = '', $type = 'username', $key = 'sub')
    {
        if (is_array($uid)) {
            if (isset($uid['username']) && ! empty($uid['username'])) {
                return $uid['username'];
            }
            if (isset($uid['email']) && ! empty($uid['email'])) {
                if ($key == 'sub') {
                    $email = explode('@', $uid['email']);
                    return $uid['email'] = substr($uid['email'], 0, 2) . '*' . $email[1];
                } else {
                    return $uid['email'];
                }
            }
            if (isset($uid['mobile']) && ! empty($uid['mobile'])) {
                if ($key == 'sub') {
                    return $uid['mobile'] = substr($uid['mobile'], 0, 3) . '****' . substr($uid['mobile'], 7, 4);
                } else {
                    return $uid['mobile'];
                }
            }
            return '';
        } else {
            $where = array();
            $where['uid'] = $uid;
            $info = $this->where($where)->find();
            
            if (isset($info['username']) && ! empty($info['username'])) {
                return stripslashes($info['username']);
            }
            
            if (isset($info['email']) && ! empty($info['email'])) {
                if ($key == 'sub') {
                    $email = explode('@', $info['email']);
                    return $info['email'] = substr($info['email'], 0, 2) . '*' . $email[1];
                } else {
                    return $info['email'];
                }
            }
            if (isset($info['mobile']) && ! empty($info['mobile'])) {
                if ($key == 'sub') {
                    return $info['mobile'] = substr($info['mobile'], 0, 3) . '****' . substr($info['mobile'], 7, 4);
                } else {
                    return $info['mobile'];
                }
            }
            if (isset($info[$type]) && ! empty($info[$type])) {
                return $info[$type];
            }
            return '';
        }
    }

    /**
     * 获取用户名，版本2
     *  add time 2015-12-3
     * 需要版本号，和来源，待完善
     */
    public function getUserName($uid){
        $where = array();
        $where['uid'] = $uid;
        $info = $this->where($where)->getField('username');

        if (isset($info) && ! empty($info) ){
            return $info;
        }

        return '';
    }

    /**
     * 获取用户的余额
     */
    public function getUserMoney($uid){
        $where = array();
        $where['uid'] = $uid;
        $money = $this->where($where)->getField('money');

        if (isset($money) && ! empty($money)) {
            return $money;
        }

        return '';
    }

    /**
     * 获取用户的头像
     */
    public function getUserPhoto($uid){
        $where=array();
        $where['uid']=$uid;
        $img=$this->where($where)->getField('img');

        if(isset($img) && !empty($img)){
            return C('CDN_DOMAIN') . C('UPLOAD_PATH') .$img;
        }

        return $img;
    }

    /**
     * 获取用户的手机号码
     */
    public function getUserPhone($uid){
        $where = array();
        $where['uid']= $uid;
        $phone = $this->where($where)->getField('mobile');

        if(isset($phone) && !empty($phone)){
            return $phone;
        }

        return '';
    }

    /**
     * 根据id获取用户的收货地址列表
     */
    public function getUserAddress($uid){
        $model = new \Think\Model();

        $addressList = $model->query("SELECT __PREFIX__member_dizhi.default,__PREFIX__member_dizhi.id,__PREFIX__member_dizhi.shouhuoren,__PREFIX__member_dizhi.mobile,__PREFIX__member_dizhi.sheng,__PREFIX__member_dizhi.shi,__PREFIX__member_dizhi.xian,__PREFIX__member_dizhi.jiedao FROM `__PREFIX__member_dizhi` WHERE __PREFIX__member_dizhi.uid = '$uid'");

        if($addressList){

            $tmp = array();
            foreach($addressList as $item){
                $tmp['id'] = $item['id'];
                $tmp['address'] = $item['jiedao'];
                $tmp['province'] = $item['sheng'];
                $tmp['city'] = $item['shi'];
                $tmp['area'] = $item['xian'];
                $tmp['consignee'] = $item['shouhuoren'];
                $tmp['phone'] = $item['mobile'];

                #判断默认地址为
                if($item['default'] == 'Y'){
                    $tmp['default'] = true;
                }elseif($item['default'] == 'N'){
                    $tmp['default'] = false;
                }
                $list[] = $tmp;
            }
        }

        return $list;
    }

    /**
     * 获取用户的默认收货地址
     */
    public function getUserDefaultAddress($uid){
        $model = new \Think\Model();

        $defaultAddress = $model->query("select id,sheng,shi,xian,jiedao,shouhuoren,mobile FROM __PREFIX__member_dizhi WHERE uid='$uid' AND `default`='Y'");

        if($defaultAddress){

            $tmp = array();
            foreach($defaultAddress as $item){
                $tmp['id'] = $item['id'];
                $tmp['address'] = $item['sheng'].$item['shi'].$item['xian'].$item['jiedao'];
                $tmp['consignee'] = $item['shouhuoren'];
                $tmp['phone'] = $item['mobile'];

                $list[] = $tmp;
            }
        }

        return $list;
    }

    /**
     * 创建用户
     */
    public function createMember(){

    }

    /**
     * 用户中心
     * 用户中心需要展示
     * return 用户图像
     *        用户名
     *        余额
     */
    public function userCenter($uid){
        $where = array();
        $where['uid'] = $uid;

        $userInfo = $this->where($where)->getField('uid,username,img,money');

//        var_dump($userInfo);
        if($userInfo){

            $tmp = array();
            foreach($userInfo as $item){
                $tmp['id'] = $item['uid'];
                $tmp['username'] = $item['username'];
                $tmp['img'] = $item['img'];
                $tmp['money'] = $item['money'];

                $list[] = $tmp;
            }
        }

        return $list;

    }

    /**
     * 用户信息页面
     *用户个人页面需要展示
     * 用户图像
     * 用户id
     * 昵称
     * 手机号码
     */
    public function getUserMessage($uid){
        $where = array();
        $where['uid'] = $uid;

        $userMessage = $this->where($where)->getField('uid,username,img,mobile');

       if($userMessage){

           $tmp = array();
           foreach($userMessage as $item){
               $tmp['id'] = $item['uid'];
               $tmp['username'] = $item['username'];
               $tmp['img'] = $item['img'];
               $tmp['mobile'] = $item['mobile'];

               $list[] = $tmp;
           }
       }
        return $list;
    }

    /** Set Function Start **/
    /**
     * 设置用户的用户名
     * $uid 用户id
     * $username 用户名
     */
    public function setUserName($uid,$username){
        $where = array();
        $where['uid'] = $uid;
        $data['username'] = $username;
        $result = $this->where($where)->save($data);

        if($result == 1){
            $result = 'ok';
        }else{
            $result = 'error';
        }

        return $result;
    }

    /**
     * 用户设置手机号码
     */
    public function setUserPhone($uid,$phone){
        $where = array();
        $where['uid'] = $uid;
        $data['mobile'] = $phone;

        $result = $this->where($where)->save($data);

        if($result == 1){
            $result = 'ok';
        }else{
            $result = 'error';
        }

        return $result;
    }

    /**
     * 用户修改用户的收获地址
     */
    public function updateUserAddress($id,$addressid,$content){
        $model = new \Think\Model();

        $condition['id'] = $addressid;
        $condition['uid'] = $id;
        $result = $model->table("__MEMBER_DIZHI__")->where($condition)->find();
        if($result){
            $where['id'] = $addressid;
            $content = explode(":",$content);
            $data['sheng'] = $content[0];
            $data['shi'] = $content[1];
            $data['xian'] = $content[2];
            $data['jiedao'] = $content[3];
            $data['youbian'] = $content[4];
            $data['shouhuoren'] = $content[5];
            $data['mobile'] = $content[6];
//            $data['default'] = 'N';
            $data['time'] = time();
            $result = $model->table("__MEMBER_DIZHI__")->where($where)->save($data);

            if($result == 1){
                return true;
            }else{
                return false;
            }
        }else{
          return  false;
        }
    }

    /**
     * 添加用户的收货地址
     */
    public function addUserAddress($uid,$content,$default)
    {
        $model = new \Think\Model();

        $content = explode(":",$content);
       if(count($content) != 7){
          return false;
       }else{
           $data['uid'] = $uid;
           $data['sheng'] = $content[0];
           $data['shi'] = $content[1];
           $data['xian'] = $content[2];
           $data['jiedao'] = $content[3];
           $data['youbian'] = $content[4];
           $data['shouhuoren'] = $content[5];
           $data['mobile'] = $content[6];

           //判断是否用户设置为默认地址
           if($default){
               $data['default'] = 'Y';

               #查看用户是否存在默认地址，如果存在默认地址，将其改变为N
               $where['uid'] = $uid;
               $where['default'] = "Y";
               $result = $model->table("__MEMBER_DIZHI__")->field('id')->where($where)->find();

               if($result){
                   $condition['id'] = $result['id'];
                   $data2['default'] = 'N';
                   $result = $model->table("__MEMBER_DIZHI__")->where($condition)->data($data2)->save();

                   if(!$result){
                       return false;
                   }
               }

           }else{
               $data['default'] = 'N';
           }

           $data['time'] = time();

           $result = $model->table("__MEMBER_DIZHI__")->data($data)->add();

           if($result){
               return true;
           }else{
               return false;
           }
       }
    }

    /**
     * 用户删除的收货地址
     */
    public function delUserAddress($uid,$id){
        $model = new \Think\Model();

        $condition['id'] = $id;
        $condition['uid'] = $uid;

        $result = $model->table("__MEMBER_DIZHI__")->where($condition)->find();
        #如果地址id与用户id存在对应关系
        if($result){
            $where['id'] = $id;
            $result = $model->table("__MEMBER_DIZHI__")->where($where)->delete();
            #每次只能删除一个地址
            if($result == 1){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 用户设置地址为默认地址
     */
    public function userAddDefaultAddr($uid,$addressId){
        $model = new \Think\Model();
        #先判断用户的uid与当前的地址id是否对应
        #再判断当前用户是否存在默认地址，如果存在默认地址，去掉默认，修改当前的id为默认地址
        $condition['id'] = $addressId;
        $condition['uid'] = $uid;

        $result = $model->table("__MEMBER_DIZHI__")->where($condition)->find();#先判断用户的uid与当前的地址id是否对应

        if($result){
            #查找用户的原来默认地址
            $condition2['uid'] = $uid;
            $condition2['default'] = "Y";

            $this->startTrans();//开启事务
            $result = $model->table("__MEMBER_DIZHI__")->where($condition2)->find();
            #如果操作之前用户存在着默认，修改原来的默认地址

            if($result['default'] == "Y"){
                #去掉用户原来的默认地址
                $where2['id'] = $result['id'];
                $data2['default'] = "N";
                $ret2 = $model->table("__MEMBER_DIZHI__")->where($where2)->data($data2)->save();

                #添加新的默认地址
                $where['id'] = $addressId;
                $data['default'] = "Y";
                $ret = $model->table("__MEMBER_DIZHI__")->where($where)->data($data)->save();

                if($ret2 && $ret){
                    return $this->commit();
                }else{
                    $this->rollback();
                    return false;
                }
            }else{
                #添加新的默认地址
                $where['id'] = $addressId;
                $data['default'] = "Y";
                $ret = $model->table("__MEMBER_DIZHI__")->where($where)->data($data)->save();

                if($ret){
                   return $this->commit();
                }else{
                    $this->rollback();
                    return false;
                }
            }
        }else{
            return false;
        }
    }

    /**
     * 点击点击商品，进入其他用户的个人中心显示的所有数据
     * 参数用户的id
     */
    public function getOtherMessage($uid){
        $model = new \Think\Model();

        $message = array();#定义返回的数组

        #根据用户的id获取用户的用户名与图像
        $condition['uid'] = $uid;
        $userResult = $model->table('__MEMBER__')->where($condition)->field('username,img')->find();

        if($userResult){
            $message['user']['name'] = $userResult['username'];
            $message['user']['photo'] = $userResult['img'];
            $message['user']['id'] = $uid;
        }else{
            return false;
        }

//        #获取用户的最新参与记录，30条。
//        $joinResult = $model->table('__MEMBER_GO_RECORD__')->where($condition)->find();
//
//        #获取用户的中奖记录，30条
//        $condition2['uid'] = $uid;
//        $condition2['huoqu'] = array('neq',0);
//        $query = "select ";
//        $winResult = $model->table('__MEMBER_GO_RECORD__')->where($condition2)->field('shopid,shopname,shopqishu,')->find();


        #晒单30
//       $condition3['sd_userid'] = $uid;
//        $shareResult = $model->table('__SHAIDAN__')->where($condition3)->field('sd_id,sd_title,sd_content,sd_time,sd_thumbs')->select();
//
//        if($shareResult){
//            $tmp =array();
//            foreach($shareResult as $item){
//                $tmp['id'] = $item['sd_id'];
//                $tmp['title'] = $item['sd_title'];
//                $tmp['content'] = $item['sd_content'];
//                $tmp['time'] = $item['sd_time'];
//                $tmp['img'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['sd_thumbs'];
//
//                $shareOrder[] = $tmp;
//            }
//        }
//        #判断用户的晒单结果，如果用户的晒单为空，则返回用户的晒单的结果为空
//        if($shareOrder){
//            $message['shareOrder'] = $shareOrder;
//        }else{
//            $message['shareOrder'] = '';
//        }

        #用户的心愿单，直接返回空
       # $message['wish'] = '';
        return $message;
    }

    /**
     * 商品中奖,显示商品的状态
     * 参数：uid和gid,用户id和商品id
     */
    public function showMyWinGoodsStatusMsg($uid,$gid){
        #定义返回的数据
        $ret = array();
        #查询用户id与当前商品的中奖人id是否对应
        $model = new \Think\Model();

        $condition['id'] = $gid;
        $condition['q_uid'] = $uid;
        $result = $model ->table('__SHOPLIST__')->field('id')->where($condition)->find();
        #存在对应
        if($result){
            $condition2['uid'] = $uid;
            $condition2['goods_id'] = $gid;
            #判断用户是否选择收货地址
            $delivery = $model->table('__DELIVERY__')->where($condition2)->find();
            #如果用户存在了收货地址
            if($delivery){
                #获取收货地址
                $where['id'] = $delivery['address_id'];
                $addr = $model->table('__MEMBER_DIZHI__')->where($where)->field('sheng,shi,xian,jiedao,shouhuoren,mobile')->find();

                #封装返回数组的信息
                $ret['consignee'] = $addr['shouhuoren'];#收货人
                $ret['address'] = $addr['sheng'].$addr['shi'].$addr['xian'];#收货人的省市区
                $ret['street'] = $addr['jiedao'];#街道
                $ret['mobile'] = $addr['mobile'];

                #获取商品的发货状态
                $where2['shopid'] = $gid;
                $where2['uid'] = $uid;
                $where2['huode'] = array('neq',0);
                $status = $model->table('__MEMBER_GO_RECORD__')->where($where2)->field('status')->find();
                #分析status
                $status = explode(',',$status['status']);

                #分析状态
                if($status[1] == '未发货'){
                    $ret['status'] = 'afterDelivery';#等待发货
                }elseif($status[1] == '已发货' && $status[2] == '待收货'){
                    $ret['status'] = 'toconfirm';#已发货，带确认收货
                }elseif($status[1] === '已发货' && $status[2] == '已完成'){
                    $ret['status'] = 'completed';#已完成
                }else{
                    $ret['status'] = null;
                }
            }else{
                $ret['deliveryAddr'] = null;
            }

            #显示用户的中奖商品的信息,包含商品的信息和用户的购买信息
            $goodsMessage =  $model->query("select __PREFIX__shoplist.id,__PREFIX__shoplist.title,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.thumb,__PREFIX__shoplist.q_end_time,__PREFIX__shoplist.q_user_code,__PREFIX__shoplist.q_uid from __PREFIX__shoplist where __PREFIX__shoplist.id = ".$gid);

            $ret['goods'] = array();
            foreach($goodsMessage as $item){
                $ret['goods']['img'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];#商品的缩略图
                $ret['goods']['name'] = $item['title'];#商品的名称
                $ret['goods']['periods'] = $item['qishu'];#商品的期数
                $ret['goods']['endtime'] = date("Y-m-d H:i:s",$item['q_end_time']);#商品的结束时间
                $ret['goods']['lucklyNumber'] = $item['q_user_code'];#商品的幸运号码
                #用户的购买数量
                $ret['goods']['userBuyCount'] = $model->query("select SUM(__PREFIX__member_go_record.gonumber) as gonumber from __PREFIX__member_go_record WHERE  __PREFIX__member_go_record.uid = ".$uid." and __PREFIX__member_go_record.shopid=".$item['id'])[0]['gonumber'];
            }
        }else{
            #不存在对应
            return false;
        }

        return $ret;
    }

    /**
     * @param $uid 用户id
     * @param $addrid 地址id
     * @param $gid 商品id
     */
    public function addGoodsSendAddr($uid,$addrid,$gid){
        #返回用户的选择的地址信息
        $ret = array();

        $model = new \Think\Model();

        $data['address_id'] = $addrid;
        $data['goods_id'] = $gid;
        $data['uid'] = $uid;

        #判断用户地址和用户是否对应
        $condition['uid'] = $uid;
        $condition['id'] = $addrid;

        $address = $model->table('__MEMBER_DIZHI__')->where($condition)->find();
        if($address){
            #在插入数据之前先判断数据当前用户和当前商品的id是否已经存在于delivery表中
            $where['uid'] = $uid;
            $where['goods_id'] = $gid;
            $exist = $model ->table("__DELIVERY__")->where($where)->find();
            if($exist){
                return false;
            }

           $result = $model->table("__DELIVERY__")->add($data);

            #判断是否插入成功
            if($result){
                #返回插入成功的用户收货地址数据
                $condition2['id'] = $result;
                $addressid = $model->table("__DELIVERY__")->where($condition2)->getField('address_id');

                $addressResult = $model->query("select sheng,shi,xian,jiedao,mobile,shouhuoren from __PREFIX__member_dizhi INNER JOIN __PREFIX__delivery ON __PREFIX__member_dizhi.id = __PREFIX__delivery.address_id where __PREFIX__member_dizhi.id = ".$addressid);

                if($addressResult){
                    #封装返回地址信息
                    foreach($addressResult as $item){
                        $ret['address'] = $item['sheng'].$item['shi'].$item['xian'];
                        $ret['street'] = $item['jiedao'];
                        $ret['consignee'] = $item['shouhuoren'];#收货人
                        $ret['mobile'] = $item['mobile'];
                    }
                    return $ret;
                }else{
                    Mylog::write($model->getLastSql());
                    Mylog::write('地址连接查询错误');
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    /**
     * 用户修改收货地址
     */
    public function updateGoodsSendAddr($uid,$addrid,$gid){
        #返回用户的选择的地址信息
        $ret = array();

        $model = new \Think\Model();

        $data['address_id'] = $addrid;

        #判断用户地址和用户是否对应
        $condition['uid'] = $uid;
        $condition['id'] = $addrid;

        $address = $model->table('__MEMBER_DIZHI__')->where($condition)->find();

        #存在对应
        if($address){
            $condition2['uid'] = $uid;
            $condition2['goods_id'] = $gid;
            $deliverResult = $model ->table("__DELIVERY__")->where($condition2)->save($data);

            if($deliverResult){
                $updateResult = $model->query("select sheng,shi,xian,jiedao,mobile,shouhuoren from __PREFIX__member_dizhi INNER JOIN __PREFIX__delivery ON __PREFIX__member_dizhi.id = __PREFIX__delivery.address_id where __PREFIX__delivery.uid = ".$uid." and __PREFIX__delivery.goods_id = ".$gid);
                #封装返回数组
                if($updateResult){
                    foreach($updateResult as $item){
                        $ret['address'] = $item['sheng'].$item['shi'].$item['xian'];
                        $ret['street'] = $item['jiedao'];
                        $ret['consignee'] = $item['shouhuoren'];#收货人
                        $ret['mobile'] = $item['mobile'];
                    }
                    return $ret;
                }else{
                    Mylog::write($model->getLastSql());
                    Mylog::write('地址连接查询错误');
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 用户确认收货
     */
    public function confirmGetGoods($uid,$gid){
        #判断用户与中奖商品id与中奖用户的关系
        $model = new \Think\Model();

        $condition['id'] = $gid;#商品id
        $condition['q_uid'] = $uid;#商品表中商品中奖的信息

        $exist = $model->table("__SHOPLIST__")->where($condition)->find();

        if(!$exist){
            return false;
        }else{
            #在用户用户购买记录表中修改状态
            $data['status'] = '已付款,已发货,已完成';
            $where['shopid'] = $gid;
            $where['uid'] = $uid;

            $result = $model->table("__MEMBER_GO_RECORD__")->where($where)->save($data);

            if($result){
                return true;
            }else{
                return false;
            }
        }

    }

    /* end of Member Model*/
}